<template>
  <div style="display: inline-block" v-loading="loading">
    <el-upload
      style="display: inline-block"
      action
      :accept="fileType"
      :limit="1"
      :on-exceed="handleExceed"
      :http-request="uploadFile"
      :show-file-list="showList === true"
      :before-upload="beforeAvatarUpload"
      ref="upload"
    >
      <div v-if="type == 1">
        <img v-if="imageUrl" :src="imageUrl" class="avatar" />
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      </div>
      <el-button v-else size="mini" :type="buttonType">{{ title }}</el-button>
    </el-upload>
  </div>
</template>

<script>
import Api from "@/api/project/file";
export default {
  props: {
    fileType: { String, default: "*" },
    title: { String, default: "点击上传" },
    limit: { Number, default: 1 },
    showList: { Boolean, default: "" },
    sizeLimit: { Number, default: 20 },
    type: { Number, default: 1 },
    buttonType: {String,default: 'primary'}
  },
  data() {
    return {
      loading: false,
      show: false,
    };
  },
  methods: {
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      );
    },
    beforeAvatarUpload(file) {
      const fileTypeName = file.name.substring(file.name.lastIndexOf("."));
      const extension = this.fileType ==='*'?true:this.fileType.includes(fileTypeName);
      const isLt2M = file.size / 1024 / 1024 < this.sizeLimit;
      if (!extension) {
        this.$message.error(`只能上传${this.fileType}类型文件`);
        return false;
      }
      if (!isLt2M) {
        this.$message.error(`上传文件大小不能超过 ${this.sizeLimit}MB!`);
      }
      return extension && isLt2M;
    },
    uploadFile(param) {
      this.loading = true;
      var formData = new FormData();
      formData.append("file", param.file);
      this.$emit("loading", true);
      Api.upload(formData)
        .then((data) => {
          this.clear();
          this.loading = false;
          this.$emit("loading", false);
          this.$emit("success", data);
        })
        .catch((response) => {
          this.clear();
          this.$emit("loading", false);
          this.loading = false;
          this.$message.error(response.msg);
        });
    },
    clear() {
      this.$refs.upload.clearFiles();
    },
  },
};
</script>

<style>
</style>